package com.ruoyi.system.service.impl;

import java.beans.Transient;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.constant.RentConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.mapper.EntityDeviceMapper;
import com.ruoyi.system.mapper.EntitySequenceMapper;
import com.ruoyi.system.mapper.RentDeviceLinkMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.EntityRentMapper;
import com.ruoyi.system.service.IEntityRentService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import static com.ruoyi.common.constant.RentConstants.RENT_TYPE_RENTING;
import static com.ruoyi.common.constant.RentConstants.RENT_TYPE_REVOKED;

/**
 * 【请填写功能名称】Service业务层处理
 * 
 * @author ruoyi
 * @date 2020-12-27
 */
@Service
public class EntityRentServiceImpl implements IEntityRentService 
{
    @Autowired
    private EntityRentMapper entityRentMapper;
    @Autowired
    private RentDeviceLinkMapper rentDeviceLinkMapper;
    @Autowired
    private EntityDeviceMapper entityDeviceMapper;
    @Autowired
    private EntitySequenceMapper entitySequenceMapper;

    /**
     * 查询【请填写功能名称】
     * 
     * @param id 【请填写功能名称】ID
     * @return 【请填写功能名称】
     */
    @Override
    public EntityRent selectEntityRentById(Long id) {
        EntityRent result = entityRentMapper.selectEntityRentById(id);
        RentDeviceLink rentDeviceLink = new RentDeviceLink();
        rentDeviceLink.setRentId(id);
        result.setRentDeviceList(rentDeviceLinkMapper.selectRentDeviceLinkList(rentDeviceLink));
        return result;
    }

    /**
     * 查询【请填写功能名称】列表
     * 
     * @param entityRent 【请填写功能名称】
     * @return 【请填写功能名称】
     */
    @Override
    public List<EntityRent> selectEntityRentList(EntityRent entityRent) {
        List<EntityRent> entityRents = entityRentMapper.selectEntityRentList(entityRent);
        if(!CollectionUtils.isEmpty(entityRents)){
            RentDeviceLink rentDeviceLink = new RentDeviceLink();
            for (EntityRent rent: entityRents) {
                rentDeviceLink.setRentId(rent.getId());
                rent.setRentDeviceList(rentDeviceLinkMapper.selectRentDeviceLinkList(rentDeviceLink));
            }
        }
        return entityRents;
    }

    /**
     * 新增【请填写功能名称】
     * 
     * @param entityRent 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult insertEntityRent(EntityRent entityRent) {
        List<RentDeviceLink> rentDeviceList = entityRent.getRentDeviceList();
        List<Long> deviceIdList = new ArrayList<>();
        if(CollectionUtils.isEmpty(rentDeviceList)){
           return AjaxResult.warn("请添加出租设备!");//请添加出租设备
        }else{
            //校验添加的出租设备是否都属库存正常设备
            for(RentDeviceLink link: rentDeviceList){
                deviceIdList.add(link.getDeviceId());
            }
            //
            List<String> disAbleDevice = new ArrayList<String>();
            List<EntityDevice> entityDevices = entityDeviceMapper.queryDeviceByIds(deviceIdList);
            for(EntityDevice device: entityDevices){
                if(RentConstants.DEVICE_TYPE_IN_STOCK != device.getValid()){
                    disAbleDevice.add(device.getSerialNumber());
                }
            }
            if(!CollectionUtils.isEmpty(disAbleDevice)){
                return AjaxResult.warn("以下设备不可出租，请删除或者重新添加后再提交!不可出租设备编号："+disAbleDevice.toString());//请添加出租设备
            }
        }
        //计算 计划租赁时长
        if(null != entityRent.getPlanRentStartTime() && null != entityRent.getPlanRentEndTime()){
            int planRentSpan = DateUtils.differentDaysByMillisecond(entityRent.getPlanRentEndTime(), entityRent.getPlanRentStartTime()) + 1;
            entityRent.setPlanRentSpan(planRentSpan);
        }
        String serialNumber = "XSXR";
        serialNumber += DateUtils.dateTimeNow("YYYYMMDD");
        Long rentNumber = entitySequenceMapper.getNextValueAtMax999("rent_number");
        if(rentNumber < 10){
            serialNumber = serialNumber + "00" + rentNumber;
        }else if(rentNumber < 100){
            serialNumber = serialNumber + "0" + rentNumber;
        }else{
            serialNumber = serialNumber + rentNumber;
        }
        entityRent.setRentNumber(serialNumber);
        //生成出库单
        int result = entityRentMapper.insertEntityRent(entityRent);
        //插入出租设备
        for(RentDeviceLink link: rentDeviceList){
            link.setRentId(entityRent.getId());
            if(null != link.getPlanRentStartTime() && null != link.getPlanRentEndTime()){
                int devicePlanRentSpan = DateUtils.differentDaysByMillisecond(link.getPlanRentEndTime(), link.getPlanRentStartTime()) + 1;
                link.setPlanRentSpan(devicePlanRentSpan);
            }
        }
        rentDeviceLinkMapper.insertRentDeviceLinkList(rentDeviceList);
        entityDeviceMapper.updateDeviceValidByIds(deviceIdList,RentConstants.DEVICE_TYPE_RENTING);
        return AjaxResult.success();
    }

    /**
     * 修改【请填写功能名称】
     * 
     * @param entityRent 【请填写功能名称】
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public AjaxResult updateEntityRent(EntityRent entityRent) {
        EntityRent rent = selectEntityRentById(entityRent.getId());
        if(RENT_TYPE_RENTING != rent.getValid()){
            return AjaxResult.error("当前订单不是已出租状态，无法更新！");
        }
        if(null != entityRent.getPlanRentStartTime() && null != entityRent.getPlanRentEndTime()){
            int planRentSpan = DateUtils.differentDaysByMillisecond(entityRent.getPlanRentEndTime(), entityRent.getPlanRentStartTime()) + 1;
            entityRent.setPlanRentSpan(planRentSpan);
        }
        if(null != entityRent.getActualRentStartTime() && null != entityRent.getActualRentEndTime()){
            int actualRentSpan = DateUtils.differentDaysByMillisecond(entityRent.getActualRentEndTime(), entityRent.getActualRentStartTime()) + 1;
            entityRent.setActualRentSpan(actualRentSpan);
        }
        int result = entityRentMapper.updateEntityRent(entityRent);
        List<RentDeviceLink> rentDeviceList = entityRent.getRentDeviceList();
        EntityDevice entityDevice = new EntityDevice();
        if(!CollectionUtils.isEmpty(rentDeviceList)){
            for(RentDeviceLink link: rentDeviceList){
                link.setRentId(entityRent.getId());
                if(null != link.getPlanRentStartTime() && null != link.getPlanRentEndTime()){
                    int devicePlanRentSpan = DateUtils.differentDaysByMillisecond(link.getPlanRentEndTime(), link.getPlanRentStartTime()) + 1;
                    link.setPlanRentSpan(devicePlanRentSpan);
                }
                if(null != link.getActualRentStartTime() && null != link.getActualRentEndTime()){
                    int actualRentSpan = DateUtils.differentDaysByMillisecond(link.getActualRentEndTime(), link.getActualRentStartTime()) + 1;
                    link.setActualRentSpan(actualRentSpan);
                    entityDevice.setValid(RentConstants.DEVICE_TYPE_IN_STOCK);
                    entityDeviceMapper.updateEntityDevice(entityDevice);
                }
                entityDevice.setId(link.getDeviceId());
                if(null != link.getId() && 0 != link.getId()){
                    rentDeviceLinkMapper.updateRentDeviceLink(link);
                }else {
                    rentDeviceLinkMapper.insertRentDeviceLink(link);
                    entityDevice.setValid(RentConstants.DEVICE_TYPE_RENTING);
                    entityDeviceMapper.updateEntityDevice(entityDevice);
                }

            }
        }
        return 1==result?AjaxResult.success():AjaxResult.error();
    }

    /**
     * 删除【请填写功能名称】对象
     * 
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteEntityRentByIds(String ids)
    {
        return entityRentMapper.deleteEntityRentByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除【请填写功能名称】信息
     * 
     * @param id 【请填写功能名称】ID
     * @return 结果
     */
    @Override
    public int deleteEntityRentById(Long id)
    {
        return entityRentMapper.deleteEntityRentById(id);
    }

    /**
     * 总出库单量
     * @return
     */
    @Override
    public Long getTotalRentCount(){
        return entityRentMapper.getTotalRentCount();
    }
    /**
     * 每年出库单统计
     * @return
     */
    @Override
    public JSONObject queryEveryYearRentCount(){
        JSONObject jsonObject = new JSONObject();
        JSONArray arrayName = new JSONArray();
        JSONArray arrayValue = new JSONArray();
        List<ResultMap> resultMaps = entityRentMapper.queryEveryYearRentCount();
        if(!CollectionUtils.isEmpty(resultMaps)){
            for(ResultMap result : resultMaps){
                arrayName.add(result.getName());
                arrayValue.add(result.getCount());
            }
        }
        jsonObject.put("X", arrayName);//键名为 X
        jsonObject.put("V", arrayValue);//键名为 V
        return jsonObject;
    }
    /**
     * 过去12个月出库单统计
     * @return
     */
    @Override
    public JSONObject queryLastEveryMonthRentCount(){
        JSONObject jsonObject = new JSONObject();
        JSONArray arrayName = new JSONArray();
        JSONArray arrayValue = new JSONArray();
        List<ResultMap> resultMaps = entityRentMapper.queryLastEveryMonthRentCount();
        if(!CollectionUtils.isEmpty(resultMaps)){
            for(ResultMap result : resultMaps){
                arrayName.add(result.getName());
                arrayValue.add(result.getCount());
            }
        }
        jsonObject.put("X", arrayName);//键名为 X
        jsonObject.put("V", arrayValue);//键名为 V
        return jsonObject;
    }
    /**
     * 出库单最多的十个客户
     * @return
     */
    @Override
    public JSONObject queryTopTenCustomer(){
        JSONObject jsonObject = new JSONObject();
        JSONArray arrayName = new JSONArray();
        JSONArray arrayValue = new JSONArray();
        List<ResultMap> resultMaps = entityRentMapper.queryTopTenCustomer();
        if(!CollectionUtils.isEmpty(resultMaps)){
            for(ResultMap result : resultMaps){
                arrayName.add(result.getName());
                arrayValue.add(result.getCount());
            }
        }
        jsonObject.put("X", arrayName);//键名为 X
        jsonObject.put("V", arrayValue);//键名为 V
        return jsonObject;
    }

    /**
     * 获取出库单汇总详情
     * @param rentId
     * @return
     */
    @Override
    public EntityRent getRentInfo(Long rentId){
        EntityRent entityRent = entityRentMapper.selectEntityRentById(rentId);
        List<EntityRentDeviceLinkCollect> entityRentDeviceLinkCollects = rentDeviceLinkMapper.queryRentDeviceByRentIdAndValid(rentId, RENT_TYPE_REVOKED);
        entityRent.setValidRentDevice(entityRentDeviceLinkCollects);
        return entityRent;
    }
}
